<template>
  <el-dialog title="分配权限" :visible.sync="showPermDialog" @close="btnPermCancel">
    <!-- 权限是一颗树 -->
    <!-- 将数据绑定到组件上 -->
    <!-- check-strictly 如果为true 那表示父子勾选时  不互相关联 如果为false就互相关联 -->
    <!-- id作为唯一标识 -->
    <el-tree ref="permTree" :data="permData" :props="defaultProps" default-expand-all show-checkbox icon-class="''" check-strictly node-key="id" :default-checked-keys="selectCheck" />
    <!-- 确定 取消 -->
    <el-row slot="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button type="primary" size="small" @click="btnPermOK">确定</el-button>
        <el-button size="small" @click="btnPermCancel">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { getPermissionList } from '@/api/permission'
import { _noLimitCate } from '@/utils'
import { getRoleDetailsByIdApi, assignPerm } from '@/api/setting'
export default {
  data() {
    return {
      showPermDialog: false,
      id: '',
      permData: [], // 权限数据,
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      selectCheck: [] // 默认选中的节点
    }
  },
  methods: {
    async getPermissionList() {
      const res = await getPermissionList()
      // 将数据转换为树形数据
      this.permData = _noLimitCate(res, '0')
    },
    async open(roleId) {
      // 记录当前要分配权限的角色id
      this.id = roleId
      // 查询出所有权限树数据
      await this.getPermissionList()
      // 查询角色原来拥有的权限列表
      const { permIds } = await getRoleDetailsByIdApi(roleId)
      this.selectCheck = permIds
      this.showPermDialog = true
    },
    btnPermCancel() {
      this.showPermDialog = false
    },
    async btnPermOK() {
      // 获取更改后的数据
      const permIds = this.$refs.permTree.getCheckedKeys()
      await assignPerm({ id: this.id, permIds })
      this.$message.success('分配成功')
      this.showPermDialog = false
    }
  }
}
</script>

<style lang="scss" scoped></style>
